package test;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * @author MADAO
 */
public class CustomClassLoader extends ClassLoader {

    /**
     * 这里可以获取项目的target根目录
     */
    private final String loadPath = Objects.requireNonNull(CustomClassLoader.class.getResource("/").getPath());

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        //这里要做判断,只有项目下的类可以使用该加载器加载
        if (!name.startsWith("test")) {
            return super.loadClass(name);
        }
        //com.xx.xxx -> com/xx/xxx
        final String s = name.replaceAll("\\.", "/");
        InputStream stream = null;
        try {
            System.out.println("loadPath: " + loadPath + s + ".class");
            stream = new FileInputStream(loadPath + s + ".class");
            final int len = stream.available();
            final byte[] bytes = new byte[len];
            stream.read(bytes);
            //将byte[]转化为class对象
            return defineClass(name, bytes, 0, len);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("读取资源时出现异常");
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
